package ltd.newbee.mall.product.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping
public class OrderMockController {

    @PostMapping("/api/mock/order/create")
    @ResponseBody
    public Map<String, Object> create(HttpSession session) {
        Map<Long, Integer> cart = (Map<Long, Integer>) session.getAttribute("CART");
        if (cart == null || cart.isEmpty()) {
            cart = new HashMap<>();
        }
        String orderNo = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        List<Map<String, Object>> orders = (List<Map<String, Object>>) session.getAttribute("ORDERS");
        if (orders == null) {
            orders = new ArrayList<>();
            session.setAttribute("ORDERS", orders);
        }
        Map<String, Object> order = new HashMap<>();
        order.put("orderNo", orderNo);
        order.put("createdAt", LocalDateTime.now().toString());
        order.put("items", new HashMap<>(cart));
        orders.add(order);
        cart.clear();
        return Map.of("orderNo", orderNo);
    }

    @GetMapping("/orders")
    public String myOrders(Model model, HttpSession session) {
        List<Map<String, Object>> orders = (List<Map<String, Object>>) session.getAttribute("ORDERS");
        if (orders == null) orders = new ArrayList<>();
        model.addAttribute("orders", orders);
        return "my-orders";
    }

    @GetMapping("/orders/detail")
    public String orderDetail(String orderNo, Model model, HttpSession session) {
        List<Map<String, Object>> orders = (List<Map<String, Object>>) session.getAttribute("ORDERS");
        if (orders == null) orders = new ArrayList<>();
        Map<String, Object> found = orders.stream().filter(o -> orderNo.equals(o.get("orderNo"))).findFirst().orElse(null);
        model.addAttribute("order", found);
        return "order-detail";
    }
}



